import scipy.ndimage as ndi
import numpy as np

def getOrderedLabels(limg,nlabels,minsize=1):
    """order all the labels in limg by object size
    limg: a labeled image
    nlabels: the number of labels occuring in limg
    """
    lchist = ndi.histogram(limg,1,nlabels,nlabels)
    bins =  np.arange(1,nlabels+1)
    
    inds = np.nonzero(lchist>=minsize)[0]
    lchist = lchist.take(inds)
    bins = bins.take(inds)
    oinds = np.argsort(lchist)

    olabels = np.take(bins,oinds)
    return olabels, lchist

def getLargestLabel(limg,nlabels,minsize=1):
    """order all the labels in limg by object size
    limg: a labeled image
    nlabels: the number of labels occuring in limg
    """
    lbls,szs = getOrderedLabels(limg,nlabels,minsize=1)

    return np.where(limg==lbls[-1],1,0)
